//
//  SongViewController.swift
//  LocalMusicPlayer
//
//  Created by Darren on 16/9/23.
//  Copyright © 2016年 darren. All rights reserved.
//

import UIKit
import AVFoundation
import FreeStreamer

class SongViewController: UIViewController {

    @IBOutlet weak var toolBar: UIToolbar!
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var lrcTableView: UITableView!
    
    /**当前行*/
    var currentIndex = 0
    /**歌词数组*/
    var lrcArr = [String]()
    /**歌词时间数组*/
    var lycTimerArr = [String]()
    /**歌词定时器*/
    fileprivate var lrcTimer = CADisplayLink()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.lrcTableView.delegate = self
        self.lrcTableView.dataSource = self
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(90 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) {
            self.view.insertSubview(self.toolBar, belowSubview: self.iconView)
        }
        let duration = UIDevice.current.orientation
        if duration == .portrait {  // 竖屏
            self.lrcTableView.contentInset = UIEdgeInsetsMake(APPH*0.5, 0,APPH*0.5, 0);
        }
        // 监听状态，播放完成后自动播放下一首
        CLNotificationCenter.addObserver(self, selector: #selector(myMovieFinishedCallback), name: NSNotification.Name(rawValue: "stopPlayAutoNext"), object: nil)
    }
    deinit{
        NotificationCenter.default.removeObserver(self)
    }

    override var prefersStatusBarHidden : Bool {
        return true;
    }
    func myMovieFinishedCallback(){
        self.updateMusicLrcInfo()
    }
    // 更新歌曲歌词信息
    func updateMusicLrcInfo(){
        
        self.lrcTableView.reloadData()
        self.currentIndex = 0
        // 开启歌词的定时器
        self.startLrcTime()
        self.setupLrcArr(MusicOperationTool.shareInstance.currentModel)
        self.lrcTableView.reloadData()
    }
    override func viewDidAppear(_ animated: Bool) {
        self.setupLrcArr(MusicOperationTool.shareInstance.currentModel)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func timeStringWithString(_ timeString:String)->Float{
        let min:Double = Double(timeString.components(separatedBy: ":")[0])!
        let range = NSMakeRange(3, 2)
        let second:Double = Double((timeString as NSString).substring(with: range))!
        let haomiao:Double = Double(timeString.components(separatedBy: ".")[1])!
        let timer1 = min*60
        let timer2 = haomiao*0.01
        return (Float)(timer1+timer2+second)
    }
    func getLabWidth(_ labelStr:String,font:UIFont,height:CGFloat) -> CGFloat {
        let statusLabelText: NSString = labelStr as NSString
        let size = CGSize(width: APPW, height: height)
        let dic = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying)
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [String : AnyObject], context:nil).size
        return strSize.width
    }
    
    @IBAction func clickClosebtn() {
        self.dismiss(animated: true, completion: nil)
    }
}
//MARK: - UITableViewDelegate，UITableViewDataSource
extension SongViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lrcArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let ID = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil {
            cell = MyLrcTableViewCell(style: .default, reuseIdentifier: ID)
        }
        (cell as! MyLrcTableViewCell).selectionStyle = .none
        cell?.backgroundColor = UIColor.clear
        (cell as! MyLrcTableViewCell).lrcLable.text = lrcArr[(indexPath as NSIndexPath).row]
        
        (cell as! MyLrcTableViewCell).lrcLable.cl_centerX = self.lrcTableView.cl_centerX
        
        if(self.currentIndex == (indexPath as NSIndexPath).row){
            (cell as! MyLrcTableViewCell).lrcLable.font = UIFont.systemFont(ofSize: 25)
            let str = (cell as! MyLrcTableViewCell).lrcLable.text
            let lableW = self.getLabWidth(str!, font: UIFont.systemFont(ofSize: 25), height: 30)
            (cell as! MyLrcTableViewCell).lrcLable.cl_width = lableW
            (cell as! MyLrcTableViewCell).lrcLable.cl_centerX = self.lrcTableView.cl_centerX
            (cell as! MyLrcTableViewCell).lrcLable.textColor = UIColor.white
            
            (cell as! MyLrcTableViewCell).lrcLable.adjustsFontSizeToFitWidth = true
            (cell as! MyLrcTableViewCell).lrcLable.minimumScaleFactor = 0.1
        } else {
            (cell as! MyLrcTableViewCell).lrcLable.cl_width = APPW  // 防止cell宽度复用
            (cell as! MyLrcTableViewCell).lrcLable.cl_centerX = self.lrcTableView.cl_centerX
            (cell as! MyLrcTableViewCell).cellprogress = 0
            (cell as! MyLrcTableViewCell).lrcLable.font = UIFont.systemFont(ofSize: 15)
            (cell as! MyLrcTableViewCell).lrcLable.textColor = UIColor.white
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        lrcTableView.scrollToRow(at: indexPath, at: .middle, animated: true)
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //  当前行
        let scrllCurrentLine = Int(((scrollView.contentOffset.y+lrcTableView.cl_height*0.5)/40)+lrcTableView.cl_height*0.5/40)
        // 这个一行的时间
        if scrllCurrentLine<lycTimerArr.count{
            let scrllCurrentLineTimeStr:String = lycTimerArr[scrllCurrentLine]
            let scrllCurrentLineTime:Float = (Float)(self.timeStringWithString(scrllCurrentLineTimeStr))
            
            var position = FSStreamPosition()
            position.minute = uint(scrllCurrentLineTime/Float(60))
            position.second = uint(scrllCurrentLineTime.truncatingRemainder(dividingBy: Float(60)))
            MusicOperationTool.shareInstance.tool.audioStream.seek(to: position)
            
            self.setcurrentTime((Float)(scrllCurrentLineTime))
        }
    }
}
//MARK: - 歌词的解析
extension SongViewController{
    func setupLrcArr(_ model:musicModel) {
        let lrcTool = LrcTools()
        let dataArray = lrcTool.setupLrcArrayAndLtrTimerArr(model: model)
        self.lrcArr = dataArray[0] as! [String]
        self.lycTimerArr = dataArray[1] as! [String]
        // 开启歌词的定时器
        self.startLrcTime()
        self.lrcTableView.reloadData()
    }
    
    //开启歌词定时器
    fileprivate func startLrcTime(){
        
        lrcTimer = CADisplayLink.init(target: self, selector: #selector(SongViewController.updataLrc))
        lrcTimer.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
    }
    fileprivate func stopLrcTime(){
        self.startLrcTime()
        lrcTimer.invalidate()
    }
    @objc fileprivate func updataLrc(){
        let musicInfoModel = MusicOperationTool.shareInstance.getMusicMessageModel() as MusicMessageModel
        let dur:Float = Float(musicInfoModel.totalTime)
        let currTimer = MusicOperationTool.shareInstance.tool.audioStream.currentTimePlayed.position*dur
        self.setcurrentTime(currTimer)
    }
    
    fileprivate func setcurrentTime(_ currentTime:Float){
        let currentTime = currentTime
        // 当前播放的时间  4.467947662
        let minute:Int = Int(currentTime) / 60;
        let second:Int = Int(currentTime) % 60;
        let msecond:Int = Int(currentTime*100) - Int(currentTime)*100
        let currentTimeStr = String(format: "%02d:%02d.%02d",arguments:[minute,second,msecond])
        
        let currentShijian = self.timeStringWithString(currentTimeStr)
        
        let count = lycTimerArr.count
        for index in 0..<count {
            // 时间数组中每行的时间
            let currentLineTime:String = lycTimerArr[index]
            
            // 下一行的时间
            var nextLineTime = String()
            let nextIdx = index + 1
            var nextLineTimeDoubla:Float = 0
            
            if nextIdx < lycTimerArr.count {
                nextLineTime = lycTimerArr[nextIdx]
                nextLineTimeDoubla = self.timeStringWithString(nextLineTime)
            }
            if currentIndex == index {
                // 拿到当期位置的cell
                let indexPath = IndexPath.init(item: currentIndex, section: 0)
                let cell = self.lrcTableView.cellForRow(at: indexPath) as? MyLrcTableViewCell
                
                let currentLineStr:String = lycTimerArr[currentIndex]
                let currentLineTimer = self.timeStringWithString(currentLineStr)
                
                // 更新进度
                let progress = (currentShijian-currentLineTimer)/(nextLineTimeDoubla-currentLineTimer)
                cell?.cellprogress = CGFloat(progress)
            }
            
            if (currentTimeStr.compare(currentLineTime)==ComparisonResult.orderedAscending)==false && currentTimeStr.compare(nextLineTime)==ComparisonResult.orderedAscending && (currentIndex==index)==false {
                // 刷新tableView
                let reloadRows = [IndexPath.init(row: currentIndex, section: 0),IndexPath.init(row: index, section: 0)]
                
                currentIndex = index
                lrcTableView.reloadRows(at: reloadRows, with: .none)
                let indexPath = IndexPath.init(row: index, section: 0)
                lrcTableView.scrollToRow(at: indexPath, at: .middle, animated: true)
            }
            
            for index2 in 0..<count {
                let indexPath1 = IndexPath.init(item: index2, section: 0)
                let cell1 = self.lrcTableView.cellForRow(at: indexPath1) as? MyLrcTableViewCell
                cell1?.lrcLable.cl_centerX = self.lrcTableView.cl_centerX

            }
        }
    }
    
}
